import dicService from '@/api/dicService'

export default {
  props: {
    fields: {
      type: Array,
      default () { return [] }
    },
    srcData: {
      type: Object,
      default () { return {} }
    },
    fieldsDict: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      renderFields: [],
      dictionary: {},
      labelWidth: '150px'
    }
  },
  computed: {
    style () {
      return {
        '--label-width': this.labelWidth
      }
    }
  },
  methods: {
    async setFieldsByDict (dict) {
      const fieldsConfig = dict.find(o => o.name === '字段配置').children
      const fields = []
      for (const config of fieldsConfig) {
        const { name, value, children } = config
        const fieldItem = {
          label: name,
          field: value
        }
        if (Array.isArray(children)) {
          Object.assign(fieldItem, this.buildFieldItemDetail(children))
        }
        fields.push(fieldItem)
      }
      this.renderFields = fields
    },
    buildFieldItemDetail (configList) {
      const result = Object.create(null)
      for (const { name, value } of configList) {
        result[name] = value
      }
      return result
    },
    async setDictionary () {
      const dictNames = this.renderFields.filter(o => o.dict).map(o => o.dict)
      for (const name of dictNames) {
        const res = await dicService.listDicItemByDicName(name)
        this.$set(this.dictionary, name, res)
      }
    },
    setLabelWidth (dictConfig) {
      const find = dictConfig.find(o => o.name === '标签宽度')
      if (find) {
        this.labelWidth = find.value
      }
    }
  },
  async beforeMount () {
    if (this.fieldsDict) {
      const res = await dicService.treeDicItemByDicName(this.fieldsDict)
      this.setLabelWidth(res)
      await this.setFieldsByDict(res)
    } else if (this.fields.length) {
      this.renderFields = this.fields
    }
    this.setDictionary()
  }
}
